// 商品审核
import React, { useState, useRef, useEffect } from 'react'
import { getListFindByCon, getbrandName, getClassUp, auditselect, deleteAllcheck, sortxiekun } from '../../../api/finance'
import {
  Table,
  Image,
  Space,
  Button,
  Form,
  Input,
  Select,
  Modal,
  message,
  Radio,
  RadioChangeEvent,
  Collapse,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import type { TableRowSelection } from 'antd/es/table/interface'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { stringify } from 'querystring'
// 表格
interface DataType {
  key: React.Key
  name: string
  shopNum: string
  money: string
  type: string
  id?: number
  goodsId?: number
}
export default function GoodAudit() {
  const [data, setData] = useState<any>([])
  const [pageNum, setPageNum] = useState()
  //请求数据
  const getList = () => {
    getListFindByCon({
      "goodsStatus": "5",
      "limit": 4,
      "page": 1
    }).then((res) => {
      console.log('res=====>', res)
      setData(res.data.data)
      addKey(res.data.data)
      setPageNum(res.data.totalByStatus)
    })
      .catch((err) => {
        console.log('err=====>', err)
      })
  }
  useEffect(() => {
    //请求数据
    getList()
    //获取品牌信息
    getbrandName().then((res2) => {
      let a: any = []
      res2.data.map((item: any) => {
        a.push({ value: item.brandName, label: item.brandName, id: item.brandId })
        setbrand(a)
      })
    }).catch((err2) => {
      console.log('err2=====>', err2)
    });
    //获取分类信息
    getClassUp().then((res3) => {
      let b: any = []
      // console.log('res3=====>', res3);
      res3.data.map((item: any) => {
        b.push({ value: item.categoryId, label: item.categoryName, id: item.categoryId })
        setcate(b)
      })
    }).catch((err3) => {
      console.log('err3=====>', err3)
    });
  }, [])

  const { Panel } = Collapse
  const [brand, setbrand] = useState<any[]>()
  const [cate, setcate] = useState<any[]>()
  const addForm = useRef<any>()
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Image
          width={70}
          height={50}
          src="https://img2.baidu.com/it/u=4022637212,469075301&fm=253&fmt=auto&app=120&f=JPEG?w=536&h=500"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsSernum',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'goodsDesc',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
    },
    {
      title: '状态',
      dataIndex: 'goodsTrail',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button className="add" onClick={() => restore(record)}>
            审核
          </Button>
          <Button className="add" onClick={() => Look(record)}>
            查看
          </Button>
          <Button id="del" onClick={() => showConfirm(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const [SelectedRow, setSelectedRow] = useState()
  const rowSelection = {
    onChange: (key: any, row: DataType[]) => {

      let checkArr: any = [];
      row.map(item => {
        checkArr.push(item.goodsId)
      })
      setSelectedRow(checkArr)
      console.log("checkArr", checkArr);
    },
  }
  const [ChangeType, setChangeType] = useState<string>()
  const [ChangeBrand, setChangeBrand] = useState<string>()
  //分类下拉框
  const handleChangeType = (value: string) => {
    setChangeType(value)
  }
  //品牌下拉框
  const handleChangeBrand = (value: string) => {
    setChangeBrand(value)
  }
  // 操作部分
  // （1）删除
  // 删除弹框
  const { confirm } = Modal
  const showConfirm = (record: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除这一行吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        console.log('OK', record)
        // 点击确定发起请求
        deleteAllcheck({
          "ids": [record.goodsId],
          "status": "6"
        }).then((res) => {
          console.log('res删除', res)
          getList()
        }).catch((err) => {
          console.log('err删除', err)
        });
        message.success('删除成功！')
      },
    })
  }
  //批量删除
  const batches = () => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除这些数据吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        // 点击确定发起请求
        deleteAllcheck({
          "ids": SelectedRow,
          "status": "6"
        }).then((res) => {
          console.log('res批量删除', res)
          getList()
        }).catch((err) => {
          console.log('err批量删除', err)
        });
        message.success('删除成功！')
      },
    })
  }
  const [isModalOpen, setIsModalOpen] = useState<boolean>()
  const [isModalOpen2, setIsModalOpen2] = useState<boolean>()
  // （2）审核
  const [record1, setRecord1] = useState<number>()
  const restore = (record: any) => {
    console.log('点击审核', record)
    setRecord1(record.goodsId)
    setIsModalOpen(true)
    // 点击确定发起请求
  }
  const handleOk = () => {
    console.log('valuedit', valuedit);
    deleteAllcheck({
      "ids": [record1],
      "status": `${valuedit}`
    }).then((res) => {
      console.log('res审核', res)
      getList()
    }).catch((err) => {
      console.log('err批量删除', err)
    });
    setIsModalOpen(false)
  }

  // （2）批量审核
  //批量审核
  const AuditAll = (): void => {
    setIsModalOpen(true)
    // 点击确定发起请求
    deleteAllcheck({
      "ids": SelectedRow,
      "status": `${valuedit}`
    }).then((res) => {
      console.log('res批量审核', res)
      getList()
    }).catch((err) => {
      console.log('err批量审核', err)
    });
  }
  //查看
  const Look = (record: any) => {
    console.log('点击查看', record)
    setIsModalOpen2(true)
  }
  // （3）重置
  const reset = () => {
    console.log('addForm', addForm)
    addForm.current.resetFields()
    getList()
    message.success('重置成功！')
  }
  // (4)查询
  const sreach = (values: any) => {
    console.log('查询需要的信息', values.keyword, ChangeType, ChangeBrand)
    if (!values.keyword || !ChangeType || !ChangeBrand) {
      message.success('请输入需查询的信息')
    } else {
      auditselect({
        limit: 4,
        page: 1,
        goodsName: values.keyword,
        goodsCategoryId: ChangeType,
        brandName: ChangeBrand
      }).then((res) => {
        console.log('res查询', res);
        setData(res.data.data)
        // getList()
      }).catch((err) => {

      });
    }
  }
  const [stateDefaultValue, setStateDefaultValue] = useState('请选择')

  const handleCancel = () => {
    console.log('取消审核')
    setIsModalOpen(false)
  }
  //审核弹框选项
  const [valuedit, setValuedit] = useState(1)
  const onChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value)
    setValuedit(e.target.value)
    // console.log('valuedit',valuedit);
  }
  const handleOk2 = () => {
    // console.log('确认审核');
    setIsModalOpen2(false)
  }
  const handleCancel2 = () => {
    // console.log('取消审核');
    setIsModalOpen2(false)
  }
  //下拉框
  const handleChange = (value: string) => {
    console.log(`selected ${value}`)
    sortxiekun({
      "limit": 4,
      "name": `${value}`,
      "orderNum": "1",
      "page": 1
    }).then((res) => {
      console.log('res排序====>', res);
      setData(res.data.data)
    }).catch((err) => {
      console.log('err排序====>', err);
    });
  }


  const addKey = (data: DataType[]) => {
    data.map(item => {
      item.id = Math.floor(Math.random() * 10000000000)
      return item
    })
  }
  return (
    <div>
      {/* 头部标题 */}
      <p className="head">商品审核</p>
      {/* 筛选查询 */}
      <Collapse className="collapse" defaultActiveKey={['1']}>
        <Panel header="筛选查询" key="1">
          <div className="operate-wrap">
            <div>
              <Form
                className="operate-left operate-left-item"
                onFinish={sreach}
                ref={addForm}
              >
                <Form.Item
                  label="关键词："
                  className="operate-left-item"
                  name="keyword"
                >
                  <Input placeholder="商品名称/商品货号" className="search" />
                </Form.Item>
                <Form.Item
                  label="分类："
                  className="operate-left-item"
                  name="type"
                >
                  <Space wrap>
                    <Select
                      defaultValue="请选择"
                      onChange={handleChangeType}
                      style={{ width: 120 }}
                      allowClear
                      options={cate}
                      className="drop"
                    />
                  </Space>
                </Form.Item>
                <Form.Item
                  label="品牌："
                  className="operate-left-item"
                  name="brand"
                >
                  <Space wrap>
                    <Select
                      defaultValue="请选择"
                      onChange={handleChangeBrand}
                      style={{ width: 120 }}
                      allowClear
                      options={brand}
                      className="drop"
                    />
                  </Space>
                </Form.Item>
                <Form.Item>
                  <Button
                    className="inquire operate-left-item"
                    htmlType="submit"
                  >
                    查询
                  </Button>
                  <Button className="reset operate-left-item" onClick={reset}>
                    重置
                  </Button>
                </Form.Item>
              </Form>
              <div></div>
            </div>
          </div>
        </Panel>
      </Collapse>

      <div className="operationTable">
        {/* 排序 */}
        <Form>
          <Form.Item
            label="排序："
            className="operate-left-item"
            name="state"
            initialValue={stateDefaultValue}
          >
            <Space wrap>
              <Select
                onChange={handleChange}
                style={{ width: 120 }}
                allowClear
                options={[
                  { value: 'goods_ontime', label: '按时间倒序' },
                  { value: 'goods_price_range', label: '按价格顺序' },
                  { value: 'goods_sell', label: '按销量顺序' },
                ]}
                className="drop"
              />
            </Space>
          </Form.Item>
        </Form>
        <Button onClick={batches} id="del" className="operate-left-item">
          批量删除
        </Button>
        <Button className="add" onClick={AuditAll}>
          批量审核
        </Button>
      </div>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        rowKey={item => String(item.id)}
        pagination={{ total: pageNum, defaultPageSize: 4 }}
      />

      <Modal
        title="商品审核"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <div>
          <p>审核意见</p>
        </div>
        <div>
          <Radio.Group onChange={onChange} value={valuedit}>
            <Radio value={0}>待审核</Radio>
            <Radio value={1}>已通过</Radio>
            <Radio value={2}>未通过</Radio>
          </Radio.Group>
        </div>
      </Modal>

      {/* 查看 弹框 */}
      <Modal
        title="商品详情"
        open={isModalOpen2}
        onOk={handleOk2}
        onCancel={handleCancel2}
        okText="确定"
        cancelText="取消"
      >
        <div>我是商品详情</div>
      </Modal>
    </div>
  )
}
